var userService = require('../service/users');
var ConstCode = require('../constant/ConstCode');

/**
 * 注册接口
 * @param {*} req
 * @param {*} res
 */
async function register(req, res) {
  var { username, password, email } = req.query;
  if (!username) {
    res.send({ code: ConstCode.ERROR_CODE, msg: '请输入姓名'});
  }
  if (!password) {
    res.send({ code: ConstCode.ERROR_CODE, msg: '请输入密码'});
  }
  if (!email) {
    res.send({ code: ConstCode.ERROR_CODE, msg: '邮箱未录入'});
  }
  try {
    var result = await userService.register(username, password, email);
    res.send(result);
  } catch (error) {
    res.send({
      code: ConstCode.ERROR_CODE,
      msg: error
    });
  }
};

async function login(req, res) {
  var { username, password } = req.query;
  if (!username) {
    res.send({ code: ConstCode.ERROR_CODE, msg: '请输入姓名'});
  }
  if (!password) {
    res.send({ code: ConstCode.ERROR_CODE, msg: '请输入密码'});
  }
  try {
    var user = await userService.login(username, password);
    if (user) {
      req.session.userid = user.id;
      req.session.username = user.username;
      res.send({
        code: ConstCode.SUCCESS_CODE,
        data: true
      });
    } else {
      res.send({
        code: ConstCode.SUCCESS_CODE,
        data: false
      });
    }
  } catch (error) {
    res.send({
      code: ConstCode.ERROR_CODE,
      msg: error
    });
  }
}

async function getLoginInfo(req, res) {
  var userid = req.session.userid;
  if (userid) {
    var data = await userService.getUserById(userid);
    return res.send({
      code: ConstCode.SUCCESS_CODE,
      data
    });
  } else {
    return res.send({
      code: ConstCode.SUCCESS_CODE,
      data: null
    });
  }
}

async function logout(req, res) { 
  req.session.userid = ''
  req.session.username = '';
  return res.redirect(301, '/html/user/login.html');
}

module.exports = {
  register,
  login,
  getLoginInfo,
  logout
}